import { login, logout } from '@/api/user'
import { getUserInfo } from '@/api/userInfo'
import { getCookie, setCookie, removeCookie } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getCookie('userToken'),
    userId: getCookie('userId'),
    authorityId: parseInt(getCookie('authorityId')),
    nickName: getCookie('nickName'),
    avatarUrl: getCookie('avatarUrl')
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, nickName) => {
    state.nickName = nickName
  },
  SET_AVATAR: (state, avatarUrl) => {
    state.avatarUrl = avatarUrl
  },
  SET_AUTHORITY_ID: (state, authorityId) => {
    state.authorityId = authorityId
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setCookie('userToken', data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response
        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const { nickName, avatarUrl, id } = data

        commit('SET_NAME', nickName)
        setCookie('userNickName', nickName)

        commit('SET_AVATAR', avatarUrl)
        setCookie('userAvatarUrl', avatarUrl)

        commit('SET_USER_ID', id)
        setCookie('userId', id)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeCookie('userToken') // must remove  token  first
        removeCookie('authorityId')
        removeCookie('userNickName')
        removeCookie('userAvatarUrl')
        removeCookie('userId')
        resetRouter()
        commit('RESET_STATE')
        window.location.reload()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeCookie('userToken')
      removeCookie('authorityId')
      removeCookie('nickName')
      removeCookie('avatarUrl')
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

